from flask import current_app, jsonify
from flask import redirect
from flask import request
from flask import session
from flask import url_for
import time
from info.models import User, News, Category
from info.utils.response_code import RET
from . import admin_blu
from flask import render_template
from flask import g
from info.utils.common import login_user_data
from datetime import datetime, timedelta
from info import constants, db
from info.utils.image_store import qiniu_image_store


@admin_blu.route('/add_category', methods=["POST"])
def add_category():
    """分类的添加、修改"""
    # 1.获取参数
    category_id = request.json.get("id")
    category_name = request.json.get("name")

    # 2.效验参数
    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 3.逻辑处理
    # 分类编辑操作
    if category_id:
        category = None
        try:
            category = Category.query.get(category_id)
        except Exception as error:
            current_app.logger.error(error)
            return jsonify(errno=RET.DBERR, errmsg="查询分类异常")
        if not category:
            return jsonify(errno=RET.NODATA, errmsg="分类不存在")

        # 修改分类名称
        category.name = category_name
    else:
        # 添加分类
        category = Category()
        category.name = category_name
        db.session.add(category)

    try:
        db.session.commit()
    except Exception as error:
        current_app.logger.error(error)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存分类对象异常")

    return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route('/category_type')
def category_type():
    """分类展示"""
    try:
        categories = Category.query.all()
    except Exception as error:
        current_app.logger.error(error)

    # 移除最新分类
    categories.pop(0)
    category_dict_list = []
    for category in categories if categories else []:
        category_dict_list.append(category.to_dict())

    data = {
        "categories": category_dict_list
    }

    return render_template("admin/news_type.html", data=data)


@admin_blu.route('/news_edit_detail', methods=["POST", "GET"])
def news_edit_detail():
    """新闻编辑修改接口"""
    if request.method == "GET":
        news_id = request.args.get("news_id")

        # 查询新闻
        try:
            news = News.query.get(news_id)
        except Exception as error:
            current_app.logger.error(error)

        news_dict = news.to_dict() if news else None

        # 查询所有分类
        try:
            categories = Category.query.all()
        except Exception as error:
            current_app.logger.error(error)
        # 移除最新分类
        categories.pop(0)
        category_dict_list = []
        for category in categories if categories else []:
            # 分类对象转换成字典
            category_dict = category.to_dict()
            # 添加is_selected=False不选择
            category_dict["is_selected"] = False
            if news.category_id == category.id:
                category_dict["is_selected"] = True
            category_dict_list.append(category_dict)

        data = {
            "news": news_dict,
            "categories": category_dict_list
        }

        return render_template("admin/news_edit_detail.html", data=data)

    # POST 请求新闻修改
    # 1.获取参数
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    # 2.效验参数
    if not all([title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    news = None # type:News
    try:
        news = News.query.get(news_id)
    except Exception as error:
        current_app.logger.error(error)
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

    # 3.逻辑处理
    if index_image:
        # 转换成二进制
        index_image_data = index_image.read()
        try:
            image_name = qiniu_image_store(index_image_data)
        except Exception as error:
            current_app.logger.error(error)
            return jsonify(errno=RET.THIRDERR, errmsg="图片保存到七牛云失败")
        # 有修改图片才保存
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name

    # 创建新闻对象
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content

    try:
        db.session.commit()
    except Exception as error:
        current_app.logger.error(error)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="修改新闻对象失败")

    # 4.返回值
    return jsonify(errno=RET.OK, errmsg="新闻编辑成功")


@admin_blu.route('/news_edit')
@login_user_data
def news_edit():
    """新闻编辑页面展示"""
    # 1.获取参数
    p = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    user = g.user

    # 2.效验参数
    try:
        p = int(p)
    except Exception as error:
        current_app.logger.error(error)
        p = 1

    # 3.逻辑处理
    # lazy="dynamic"如果真正用到里面的值,就会给你返回一个列表数据,如果只是简单的查询就会返回一个查询对象
    news_list = []
    current_page = 1
    total_page = 1
    # 默认条件所有新闻均可编辑
    filter = []
    # 关键字有值表示需要进行数据搜索
    if keywords:
        filter.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(p, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as error:
        current_app.logger.error(error)

    # 模型列表转字典列表
    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_edit.html", data=data)


@admin_blu.route('/news_review_detail', methods=["POST", "GET"])
@login_user_data
def news_review_detail():
    """新闻审核详情页面"""
    if request.method == "GET":
        # 1获取参数
        news_id = request.args.get("news_id")

        # 查询新闻
        try:
            news = News.query.get(news_id)
        except Exception as error:
            current_app.logger.error(error)

        news_dict = news.to_dict() if news else None

        data = {
            "news": news_dict
        }
        return render_template("admin/news_review_detail.html", data=data)

    # POST请求的时候需要带上news_id
    # 1.获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2.效验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg="action参数错误")

    # 3.逻辑处理
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象异常")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻为空")

    # 新闻存在才来进行审核
    if action == "accept":
        # 审核通过
        news.status = 0
    else:
        # 审核不通过
        reason = request.json.get("reason")
        if reason:
            news.status = -1
            news.reason = reason
        else:
            # 未填写原因
            return jsonify(errno=RET.PARAMERR, errmsg="请填写拒绝原因")

    try:
        db.session.commit()
    except Exception as error:
        current_app.logger.error(error)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存新闻异常")

    # 4.返回值
    return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route('/news_review')
@login_user_data
def news_review():
    """新闻审核页面展示"""
    # 1.获取参数
    p = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    user = g.user

    # 2.效验参数
    try:
        p = int(p)
    except Exception as error:
        current_app.logger.error(error)
        p = 1

    # 3.逻辑处理
    # lazy="dynamic"如果真正用到里面的值,就会给你返回一个列表数据,如果只是简单的查询就会返回一个查询对象
    news_list = []
    current_page = 1
    total_page = 1
    # 查询审核为通过&未审核的新闻条件
    filter = [News.status != 0]
    # 关键字有值表示需要进行数据搜索
    if keywords:
        filter.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(p, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as error:
        current_app.logger.error(error)

    # 模型列表转字典列表
    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_review.html", data=data)


@admin_blu.route('/user_list')
@login_user_data
def user_list():
    """用户列表展示"""
    # 1.获取参数
    p = request.args.get("p", 1)
    user = g.user

    # 2.效验参数
    try:
        p = int(p)
    except Exception as error:
        current_app.logger.error(error)
        p = 1

    # 3.逻辑处理
    # lazy="dynamic"如果真正用到里面的值,就会给你返回一个列表数据,如果只是简单的查询就会返回一个查询对象
    news_list = []
    current_page = 1
    total_page = 1
    if user:
        try:
            paginate = User.query.filter(User.is_admin == False).paginate(p, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
            user_list = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as error:
            current_app.logger.error(error)

    # 新闻对象列表转成字典列表
    user_dict_list = []
    for user in user_list if user_list else []:
        user_dict_list.append(user.to_admin_dict())

    data = {
        "users": user_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }

    # 4.返回值
    return render_template("admin/user_list.html", data=data)


@admin_blu.route('/user_count')
def user_count():
    # 查询总人数
    total_count = 0
    try:
        # 10001
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询月新增数
    mon_count = 0
    try:
        now = time.localtime()
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询日新增数
    day_count = 0
    try:
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询图表信息
    # 获取到当天00:00:00时间

    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 定义空数组，保存数据
    active_date = []
    active_count = []

    # 依次添加数据，再反转
    for i in range(0, 31):
        begin_date = now_date - timedelta(days=i)
        end_date = now_date - timedelta(days=(i - 1))
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {"total_count": total_count, "mon_count": mon_count, "day_count": day_count, "active_date": active_date,
            "active_count": active_count}

    return render_template('admin/user_count.html', data=data)


@admin_blu.route('/index')
@login_user_data
def admin_index():
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("admin/index.html", data=data)


@admin_blu.route('/login', methods=["POST", "GET"])
def admin_login():
    """后台登陆模块"""
    if request.method == "GET":
        # 从session中获取管理员用户数据
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", None)
        # 用户登录成功而且是管理员
        if user_id and is_admin:
            # 果然是管理员已经登录当他访问login页面的时候直接到后台管理首页
            return redirect(url_for("admin.admin_index"))

        return render_template("admin/login.html")

    # post 请求获取用户提交数据进行登陆效验
    # 1.获取参数
    username = request.form.get("username")
    password = request.form.get("password")

    # 2.效验参数
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不足")

    # 3.逻辑处理
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as error:
        current_app.logger.error(error)
        return render_template("admin/login.html", errmsg="查询管理员失败")

    # 效验用户是否存在
    if not user:
        return render_template("admin/login.html", errmsg="该账号没有权限")

    # 效验密码
    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="密码错误")

    # 使用session记录管理员登录信息
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    # 吉林是否是管理员
    session["is_admin"] = user.is_admin

    # 4.TODO：跳转到管理员首页
    return redirect(url_for("admin.admin_index"))










